import {
  addOutboundCall,
  addOutboundList,
  delOutboundCall,
  delOutboundList,
  queryOutboundCallList,
  queryOutboundList,
  updateOutboundList,
} from "@/services/orderOutbound";
import { queryOrdernumber } from "@/services/purchase";
import { uploadUrl } from "@/untils";
import {
  DrawerForm,
  ProFormDatePicker,
  ProFormDigit,
  ProFormList,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormUploadButton,
  ProTable,
} from "@ant-design/pro-components";
import { Button, Col, Form, Image, message, Popconfirm, Row } from "antd";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import { imgConfig } from "../PurchaseOrder";

const PurchaseOrder = () => {
  const [open, setOpen] = useState(false);
  const [outOpen, setOutOpen] = useState(false);
  const [listOpen, setListOpen] = useState(false);
  const [form] = Form.useForm();
  const [outPutForm] = Form.useForm();
  const [orderNumber, setOrderNumber] = useState("");
  const [currentType, setCurrentType] = useState("");
  const actionRef: any = useRef(null);
  const actionPici: any = useRef(null);
  const [currentData, setCurrentData] = useState<any>(null); // 当前项目数据
  const [currentProductId, setCurrentProductId] = useState<any>(null); //当前产品 id
  const [currentProducType, setCurrentProductType] = useState<any>(null); //当前产品 的出库状态

  const [fileList, setFileList] = useState<any>([]); // 上传图纸
  const [outPutOptions, setOutPutOptions] = useState<any>([]); //出库里的产品下拉框
  const [outPutList, setOutPutList] = useState<any>([]); // 批次列表

  const handleAddOut = () => {
    setOpen(true);
    setCurrentType("create");
    outPutForm.setFieldValue("batch_order", undefined);
  };
  const handleDel = async (id: number) => {
    const res = await delOutboundList({ id });
    if (res?.success) {
      message.success("操作成功");
      actionRef?.current?.reload();
    } else {
      message.error("操作失败，请联系管理员");
    }
  };

  // 出库操作
  const handleOut = async (data: any) => {
    setCurrentData(data);
    setCurrentProductType("create");
    setOutOpen(true);
  };

  useEffect(() => {
    if (outOpen) {
      const products = currentData?.product?.map((v: any) => ({
        label: v.product_name + "(" + v.unit + ")",
        value: v.id,
      }));
      setOutPutOptions(products);
      if (currentProducType === "create" && currentProductId) {
        queryOrderNumber(4, currentProductId);
      }
    } else {
      // setCurrentProductId("");
      setFileList([]);
      outPutForm.resetFields();
    }
  }, [outOpen, currentData, currentProductId]);

  const handleProductDetail = (id: number, record: any) => {
    setCurrentProductType("create");
    setCurrentProductId(id);
    setCurrentData(record);
    setListOpen(true);
  };

  // 获取出库批次
  const getCallList = async (
    outbound_project_id: number,
    product_id: number
  ) => {
    const res = await queryOutboundCallList({
      page: 1,
      pagesize: 999,
      outbound_project_id,
      product_id,
    });
    if (res?.success) {
      setOutPutList(res?.result?.data);
    }
  };
  useEffect(() => {
    if (listOpen && currentData && currentProductId) {
      getCallList(currentData?.id, currentProductId);
    }
  }, [listOpen, currentData, currentProductId]);
  const columns = [
    {
      title: "出库订单",
      dataIndex: "outbound_order_id",
      key: "outbound_order_id",
      width: 120,
      fixed: "left",
      search: false,
    },
    {
      title: "项目名称",
      dataIndex: "project",
      key: "project",
      width: 150,
      // fixed: 'left',21 群 21
    },
    // {
    //   title: '项目采购总数',
    //   dataIndex: 'supplierName',
    //   key: 'supplierName',
    //   width: 200,
    //   search: false
    // },
    {
      title: "项目出库产品",
      dataIndex: "product",
      key: "product",
      width: 200,
      search: false,
      render: (product: any, record: any) =>
        product?.map(
          (item: { product_name: string; id: number }, index: number) => {
            return (
              <span>
                <a onClick={() => handleProductDetail(item.id, record)}>
                  {item?.product_name}
                </a>
                {product.length === index + 1 ? "" : " , "}
              </span>
            );
          }
        ),
    },
    {
      title: "项目地址",
      dataIndex: "shopping_address",
      key: "shopping_address",
      width: 130,
    },
    {
      title: "项目截止日期",
      dataIndex: "project_endtime",
      key: "project_endtime",
      width: 150,
      search: false,
      render: (time: string) => dayjs(Number(time) * 1000).format("YYYY-MM-DD"),
    },
    {
      title: "废料回收",
      dataIndex: "waste",
      key: "waste",
      width: 80,
      valueEnum: {
        0: { text: "否" },
        1: { text: "是" },
      },
    },
    {
      title: "项目状态",
      dataIndex: "status",
      key: "status",
      width: 100,
      // fixed: 'right',
      align: "center",
      valueEnum: {
        0: { text: "待发货", status: "Default" },
        1: { text: "发货中", status: "Success" },
        2: { text: "已完结", status: "Success" },
      },
    },
    {
      title: "操作",
      key: "action",
      width: 150,
      fixed: "right",
      search: false,
      render: (_, record: any) => (
        <>
          <a style={{ marginRight: 8 }} onClick={() => handleViewEdit(record)}>
            编辑
          </a>
          <a style={{ marginRight: 8 }} onClick={() => handleOut(record)}>
            出库
          </a>
          <a
            style={{ marginRight: 8 }}
            onClick={() => handleViewDetail(record)}
          >
            查看
          </a>
          <Popconfirm
            title="提示"
            description="确认删除该出库订单吗？"
            onConfirm={() => handleDel(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];

  const product_columns: any = [
    // 1. 出库明细（批次）
    {
      title: "出库批次",
      dataIndex: "batch_order",
      key: "batch_order",
      width: 180,
      fixed: "left",
      search: true,
    },

    // 2. 出库日期（带时分秒）
    {
      title: "出库日期",
      dataIndex: "outbound_time",
      key: "outbound_time",
      width: 150,
      render: (time: string) => dayjs(Number(time) * 1000).format("YYYY-MM-DD"),
    },

    // 3. 出库数量
    {
      title: "出库数量",
      dataIndex: "outbound_num",
      key: "outbound_num",
      valueType: "digit",
      width: 100,
      align: "right",
    },
    {
      title: "送货单照片",
      dataIndex: "pic",
      key: "pic",
      search: false,
      width: 150,
      render: (text: string, record: any) => {
        const list = text?.split(",")?.map((v: string) => imgConfig.url + v);
        return record?.pic ? (
          <Image.PreviewGroup items={list}>
            <Image width={100} height={100} src={list?.[0]} />
          </Image.PreviewGroup>
        ) : (
          "未上传"
        );
      },
    },
    {
      title: "操作",
      key: "action",
      search: false,
      width: 100,
      fixed: "right",
      render: (_: any, record: any) => (
        <>
          <Popconfirm
            title="提示"
            description="确定删除该批次吗？"
            onConfirm={() => handleDelOutboundList(record?.id)}
            okText="确定"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];

  const handleDelOutboundList = async (id: number) => {
    const res = await delOutboundCall({
      id
    });
    if (res?.success) {
      message.success("操作成功");
      getCallList(currentData?.id, currentProductId); 
      // getCallList(currentData?.id, currentProductId);
    }
  };
  const fetchData = async (params: any) => {
    const {
      current: page,
      pageSize: pagesize,
      project,
      shopping_address,
      status,
      waste,
    } = params;
    const res = await queryOutboundList({
      page,
      pagesize,
      project_name: project,
      outbound_address: shopping_address,
      waste: waste ? Number(waste) : undefined,
      outbound_status: !isNaN(status) ? Number(status) : undefined,
    });
    return {
      data: res?.result?.data || [],
      total: res?.total || 0,
      success: true,
    };
  };
  // 编辑
  const handleViewEdit = (data: any) => {
    setCurrentData(data);
    setCurrentType("edit");
    setOpen(true);
  };
  // 查看详情
  const handleViewDetail = (data: any) => {
    setCurrentData(data);
    setCurrentType("details");
    setOpen(true);
  };
  const checkUniqueName = (_: any, value: any) => {
    const products = form.getFieldValue("product") || [];
    const currentIndex = _.field.split(".")[1];
    const valuesSet = new Set();
    products.forEach((item: any, index: any) => {
      if (index !== Number(currentIndex)) {
        valuesSet.add(item?.product_name);
      }
    });

    if (valuesSet.has(value)) {
      return Promise.reject(new Error("产品名称不能重复"));
    }
    return Promise.resolve();
  };

  const handleCreateOutbound = async (values: any) => {
    const { project_endtime, id, product, waste } = values;
    console.log(values, "valuesvalues");
    const params = {
      ...values,
      id: currentType === "edit" ? id : undefined,
      project_endtime: dayjs(project_endtime)?.unix(),
      waste: waste ? 1 : 0,
      outbound_num: product.reduce(
        (sum, item: any) => sum + item.product_num,
        0
      ),
    };
    const res =
      currentType === "edit"
        ? await updateOutboundList(params)
        : await addOutboundList(params);
    if (res?.success) {
      message?.success(currentType === "edit" ? "编辑成功" : "新建成功");
      setOpen(false);
      actionRef?.current?.reload();
    } else {
      message?.error(
        `${currentType === "edit" ? "编辑" : "新建"}出库订单失败，请稍后再试`
      );
    }
  };
  // 生成订单号
  const queryOrderNumber = async (type: number, currentProductId?: number) => {
    const res = await queryOrdernumber({ type, product_id: currentProductId });
    if (res?.success) {
      setOrderNumber(res?.result?.generateordernumber);
      if (type === 3) {
        form.setFieldValue(
          "outbound_order_id",
          res?.result?.generateordernumber
        );
      } else if (type === 4) {
        outPutForm.setFieldValue(
          "batch_order",
          res?.result?.generateordernumber
        );
      }
    } else {
      message.error("合同编号生成失败，请稍后再试");
    }
  };
  useEffect(() => {
    if (open) {
      if (currentType === "create") queryOrderNumber(3);
      else if (currentType === "edit" || currentType === "details") {
        console.log(currentType, "currentTypecurrentType");
        form.setFieldsValue({
          ...currentData,
          project_endtime: dayjs(currentData?.project_endtime * 1000).format(
            "YYYY-MM-DD"
          ),
        });
      }
    }
  }, [open, currentType, currentData]);

  // 出库提交
  const handleOutPutSubmit = async (values: any) => {
    console.log(values, "valuesvalues");
    const { pic, outbound_time, product_id } = values;
    const pics = pic
      ?.filter((item: any) => {
        return item?.response?.success || item?.status === "done";
      })
      ?.map((item: any) => item?.response?.result?.savename || item?.url)
      ?.join(",")
      ?.replace(imgConfig?.url, "");

    const params = {
      ...values,
      pic: pics,
      product_name: outPutOptions.find((v: any) => v.value === product_id)
        ?.label,
      outbound_time: dayjs(outbound_time)?.unix(),
      outbound_project_id: currentData?.id,
    };
    console.log(params, "paramsparams");
    const res = await addOutboundCall(params);
    if (res?.success) {
      actionRef.current?.reload();
      message.success("新增出库成功");
      setOutOpen(false);
    } else {
      message.error("操作失败，请稍后再试");
    }
  };
  return (
    <>
      <ProTable
        columns={columns as any}
        request={fetchData}
        rowKey="orderId"
        pagination={{ pageSize: 10 }}
        scroll={{ x: 1200 }}
        options={false}
        actionRef={actionRef}
        toolBarRender={() => [
          <Button key="add" type="primary" onClick={handleAddOut}>
            新建出库项目
          </Button>,
        ]}
      />
      <DrawerForm
        disabled={currentType === "details"}
        title={
          currentType === "create"
            ? "新建出库项目"
            : currentType === "details"
            ? "详情"
            : "编辑出库项目"
        }
        width={480}
        form={form}
        open={open}
        drawerProps={{
          destroyOnClose: true,
          onClose: () => setOpen(false),
        }}
        onFinish={handleCreateOutbound}
      >
        <ProFormText
          name="id"
          placeholder="请输入"
          disabled
          width={"lg"}
          hidden
        />
        <ProFormText
          name="outbound_order_id"
          label="出库单ID"
          tooltip="系统自动生成"
          rules={[{ required: true, message: "请输入" }]}
          placeholder="请输入"
          disabled
          width={"lg"}
        />
        {/* 采购总数 */}
        <ProFormText
          name="project"
          label="项目名称"
          rules={[{ required: true, message: "请输入" }]}
          placeholder="请输入"
          width={"lg"}
        />
        {/* 收货地址 */}
        <ProFormText
          name="shopping_address"
          label="项目地址"
          rules={[{ required: true, message: "请输入收货地址" }]}
          width={"lg"}
          placeholder="请输入收货地址"
        />
        {/* 截止日期 */}
        <ProFormDatePicker
          name="project_endtime"
          label="项目截止日期"
          rules={[{ required: true, message: "请选择截止日期" }]}
          width={"lg"}
          placeholder="请选择交付截止时间"
        />

        {/* 项目状态 */}
        {/* <ProFormSelect
          name="status"
          label="项目状态"
          width={'md'}
          rules={[{ required: true }]}
          options={[
            { value: 'pending', label: '待发货' },
            { value: 'shipping', label: '发货中' },
            { value: 'completed', label: '已完结' }
          ]}
          placeholder="选择当前采购状态"
        /> */}
        <ProFormSwitch name="waste" label="是否废料回收" />
        <ProFormList
          name="product"
          label="产品列表"
          creatorButtonProps={{
            creatorButtonText: "添加产品",
          }}
          min={0.01}
          copyIconProps={false}
          deleteIconProps={{ tooltipText: "删除" }}
          creatorRecord={{ product_name: "" }}
        >
          <Row gutter={10}>
            <Col span={16}>
              <ProFormText
                label="产品名称"
                name={"product_name"}
                width="md"
                placeholder="请输入"
                rules={[
                  { required: true, message: "产品名称必填" },
                  { validator: checkUniqueName },
                ]}
              />
            </Col>
            <Col span={8}>
              <ProFormDigit
                label="数量"
                name={"product_num"}
                min={0.01}
                max={9999999}
                width="md"
                fieldProps={{
                  precision: 0,
                  addonAfter: (
                    <ProFormSelect
                      noStyle
                      width={60}
                      allowClear={false}
                      initialValue={"个"}
                      name={"unit"}
                      style={{ width: 60 }}
                      options={[
                        { label: "个", value: "个" },
                        { label: "片", value: "片" },
                        { label: "吨", value: "吨" },
                      ]}
                    ></ProFormSelect>
                  ),
                }}
                placeholder="请输入"
                rules={[
                  { required: true, message: "产品名称必填" },
                  { validator: checkUniqueName },
                ]}
              />
            </Col>
          </Row>
        </ProFormList>
      </DrawerForm>

      <DrawerForm
        title="出库"
        width={380}
        open={outOpen}
        form={outPutForm}
        drawerProps={{
          destroyOnClose: true,
          onClose: () => setOutOpen(false),
        }}
        onFinish={handleOutPutSubmit}
      >
        <ProFormText
          name="batch_order"
          label="出库批次"
          disabled
          tooltip={"选择产品后系统自动生成"}
          placeholder="请输入出库批次"
          rules={[{ required: true, message: "请输入出库批次" }]}
          width={"md"}
        />
        <ProFormText
          name="outbound_project_id"
          label="出库批次"
          tooltip={"系统自动生成"}
          placeholder="请输入出库批次"
          width={"md"}
          hidden
        />
        <ProFormSelect
          name="product_id"
          label="产品"
          rules={[{ required: true, message: "请选择项目产品" }]}
          placeholder="请选择项目产品"
          width={"md"}
          options={outPutOptions}
          onChange={(e) => {
            queryOrderNumber(4, e);
          }}
        />
        <ProFormDigit
          name="outbound_num"
          label="产品订单数量"
          min={0.01}
          rules={[{ required: true, message: "请输入产品订单数量" }]}
          fieldProps={{ precision: 0 }}
          placeholder="请输入产品订单数量"
          width={"md"}
        />
        <ProFormDigit
          name="product_price"
          label="产品单价（未税）"
          min={0.01}
          rules={[{ required: true, message: "请输入产品单价" }]}
          fieldProps={{ precision: 2, addonAfter: "元" }}
          placeholder="请输入产品单价"
          width={"md"}
        />
        <ProFormDatePicker
          name="outbound_time"
          label="出库日期"
          width="md"
          rules={[{ required: true, message: "请选择出库日期" }]}
        />
        <ProFormUploadButton
          fieldProps={{
            fileList,
            // accept: 'jpeg,jpg,png',
            listType: "picture-card",
            // onPreview: handlePreview,
            onChange: ({ fileList: newList }) => setFileList(newList),
          }}
          name="pic"
          label="上传文件（图纸等）"
          action={uploadUrl}
        />
      </DrawerForm>
      <DrawerForm
        title="出库明细"
        width={700}
        open={listOpen}
        drawerProps={{
          destroyOnClose: true,
          onClose: () => setListOpen(false),
        }}
        onFinish={async (values) => {
          try {
            //   await onFinish(values); // 调用外部提交方法
            message.success("新增成功");
            return true;
          } catch (e) {
            message.error("提交失败，请重试");
            return false;
          }
        }}
      >
        <ProTable
          search={false}
          options={false}
          columns={product_columns}
          dataSource={outPutList}
          actionRef={actionPici}
        />
      </DrawerForm>
    </>
  );
};

export default PurchaseOrder;
